source: trunk/morituri/common/encode.py @ 367

Revision 367, 7.6 KB checked in by thomas, 3 years ago (diff)
  • morituri/program/cdparanoia.py: Add some debug.
  • morituri/common/encode.py: Add more debug. Handle the case where peak is full scale, and peakdB thus 0, which triggered not setting self.peak.
Line 
1# -*- Mode: Python; test-case-name: morituri.test.test_common_encode -*-
2# vi:si:et:sw=4:sts=4:ts=4
3
4# Morituri - for those about to RIP
5
6# Copyright (C) 2009 Thomas Vander Stichele
7
8# This file is part of morituri.
9#
10# morituri is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 3 of the License, or
13# (at your option) any later version.
14#
15# morituri is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with morituri.  If not, see <http://www.gnu.org/licenses/>.
22
23import math
24
25from morituri.common import common, task
26
27from morituri.common import log
28log.init()
29
30class Profile(object):
31    name = None
32    extension = None
33    pipeline = None
34    losless = None
35
36    def test(self):
37        """
38        Test if this profile will work.
39        Can check for elements, ...
40        """
41        pass
42
43class FlacProfile(Profile):
44    name = 'flac'
45    extension = 'flac'
46    pipeline = 'flacenc name=tagger quality=8'
47    lossless = True
48
49    # FIXME: we should do something better than just printing ERRORS
50    def test(self):
51
52        # here to avoid import gst eating our options
53        import gst
54
55        plugin = gst.registry_get_default().find_plugin('flac')
56        if not plugin:
57            print 'ERROR: cannot find flac plugin'
58            return False
59
60        versionTuple = tuple([int(x) for x in plugin.get_version().split('.')])
61        if len(versionTuple) < 4:
62            versionTuple = versionTuple + (0, )
63        if versionTuple > (0, 10, 9, 0) and versionTuple <= (0, 10, 15, 0):
64            print 'ERROR: flacenc between 0.10.9 and 0.10.15 has a bug'
65            return False
66
67        return True
68
69class AlacProfile(Profile):
70    name = 'alac'
71    extension = 'alac'
72    pipeline = 'ffenc_alac name=tagger'
73    lossless = True
74
75class WavProfile(Profile):
76    name = 'wav'
77    extension = 'wav'
78    pipeline = 'wavenc name=tagger'
79    lossless = True
80
81class WavpackProfile(Profile):
82    name = 'wavpack'
83    extension = 'wv'
84    pipeline = 'wavpackenc bitrate=0 name=tagger'
85    lossless = True
86
87class MP3Profile(Profile):
88    name = 'mp3'
89    extension = 'mp3'
90    pipeline = 'lame name=tagger quality=0 ! id3v2mux'
91    lossless = False
92
93class VorbisProfile(Profile):
94    name = 'vorbis'
95    extension = 'oga'
96    pipeline = 'audioconvert ! vorbisenc name=tagger ! oggmux'
97    lossless = False
98
99
100PROFILES = {
101    'wav':     WavProfile,
102    'flac':    FlacProfile,
103    'alac':    AlacProfile,
104    'wavpack': WavpackProfile,
105}
106
107LOSSY_PROFILES = {
108    'mp3':     MP3Profile,
109    'vorbis':  VorbisProfile,
110}
111
112ALL_PROFILES = PROFILES.copy()
113ALL_PROFILES.update(LOSSY_PROFILES)
114
115class EncodeTask(task.Task):
116    """
117    I am a task that encodes a .wav file.
118    I set tags too.
119    I also calculate the peak level of the track.
120
121    @param peak: the peak volume, from 0.0 to 1.0.  This is the sqrt of the
122                 peak power.
123    @type  peak: float
124    """
125
126    logCategory = 'EncodeTask'
127
128    description = 'Encoding'
129    peak = None
130
131    def __init__(self, inpath, outpath, profile, taglist=None):
132        """
133        @param profile: encoding profile
134        @type  profile: L{Profile}
135        """
136        assert type(inpath) is unicode, "inpath %r is not unicode" % inpath
137        assert type(outpath) is unicode, \
138            "outpath %r is not unicode" % outpath
139       
140        self._inpath = inpath
141        self._outpath = outpath
142        self._taglist = taglist
143
144        self._level = None
145        self._peakdB = None
146        self._profile = profile
147
148        self._profile.test()
149
150    def start(self, runner):
151        task.Task.start(self, runner)
152
153        # here to avoid import gst eating our options
154        import gst
155
156        self._pipeline = gst.parse_launch('''
157            filesrc location="%s" !
158            decodebin name=decoder !
159            audio/x-raw-int,width=16,depth=16,channels=2 !
160            level name=level !
161            %s !
162            filesink location="%s" name=sink''' % (
163                common.quoteParse(self._inpath).encode('utf-8'),
164                self._profile.pipeline,
165                common.quoteParse(self._outpath).encode('utf-8')))
166
167        tagger = self._pipeline.get_by_name('tagger')
168
169        # set tags
170        if self._taglist:
171            tagger.merge_tags(self._taglist, gst.TAG_MERGE_APPEND)
172
173        self.debug('pausing pipeline')
174        self._pipeline.set_state(gst.STATE_PAUSED)
175        self._pipeline.get_state()
176        self.debug('paused pipeline')
177
178        # get length
179        self.debug('query duration')
180        try:
181            length, qformat = tagger.query_duration(gst.FORMAT_DEFAULT)
182        except gst.QueryError, e:
183            self.setException(e)
184            self.stop()
185            return
186
187        # wavparse 0.10.14 returns in bytes
188        if qformat == gst.FORMAT_BYTES:
189            self.debug('query returned in BYTES format')
190            length /= 4
191        self.debug('total length: %r', length)
192        self._length = length
193
194        # add eos handling
195        bus = self._pipeline.get_bus()
196        bus.add_signal_watch()
197        bus.connect('message::eos', self._message_eos_cb)
198
199        # set up level callbacks
200        bus.connect('message::element', self._message_element_cb)
201        self._level = self._pipeline.get_by_name('level')
202        # add a probe so we can track progress
203        # we connect to level because this gives us offset in samples
204        srcpad = self._level.get_static_pad('src')
205        srcpad.add_buffer_probe(self._probe_handler)
206
207        self.debug('scheduling setting to play')
208        # since set_state returns non-False, adding it as timeout_add
209        # will repeatedly call it, and block the main loop; so
210        #   gobject.timeout_add(0L, self._pipeline.set_state, gst.STATE_PLAYING)
211        # would not work.
212
213        def play():
214            self._pipeline.set_state(gst.STATE_PLAYING)
215            return False
216        self.runner.schedule(0, play)
217
218        #self._pipeline.set_state(gst.STATE_PLAYING)
219        self.debug('scheduled setting to play')
220
221    def _probe_handler(self, pad, buffer):
222        # update progress based on buffer offset (expected to be in samples)
223        # versus length in samples
224        # marshal to main thread
225        self.runner.schedule(0, self.setProgress,
226            float(buffer.offset) / self._length)
227
228        # don't drop the buffer
229        return True
230
231    def _message_eos_cb(self, bus, message):
232        self.debug('eos, scheduling stop')
233        self.runner.schedule(0, self.stop)
234
235    def _message_element_cb(self, bus, message):
236        if message.src != self._level:
237            return
238
239        s = message.structure
240        if s.get_name() != 'level':
241            return
242
243
244        if self._peakdB is None:
245            self._peakdB = s['peak'][0]
246
247        for p in s['peak']:
248            if self._peakdB < p:
249                self.log('higher peakdB found, now %r', self._peakdB)
250                self._peakdB = p
251
252    def stop(self):
253        # here to avoid import gst eating our options
254        import gst
255
256        self.debug('stopping')
257        self.debug('setting state to NULL')
258        self._pipeline.set_state(gst.STATE_NULL)
259        self.debug('set state to NULL')
260        task.Task.stop(self)
261
262        if self._peakdB is not None:
263            self.debug('peakdB %r', self._peakdB)
264            self.peak = math.sqrt(math.pow(10, self._peakdB / 10.0))
265        else:
266            self.warning('No peak found, something went wrong!')
Note: See TracBrowser for help on using the repository browser.