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

Revision 363, 7.4 KB checked in by thomas, 3 years ago (diff)
  • doc/release: Document having clean test run.
  • morituri/common/encode.py: Catch and properly stop on gst.QueryError?. Don't set peak in stop if we had an error.
  • morituri/test/test_common_encode.py:
  • morituri/test/test_common_renamer.py:
  • morituri/test/test_image_cue.py: Clean up after tests.
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    description = 'Encoding'
127    peak = None
128
129    def __init__(self, inpath, outpath, profile, taglist=None):
130        """
131        @param profile: encoding profile
132        @type  profile: L{Profile}
133        """
134        assert type(inpath) is unicode, "inpath %r is not unicode" % inpath
135        assert type(outpath) is unicode, \
136            "outpath %r is not unicode" % outpath
137       
138        self._inpath = inpath
139        self._outpath = outpath
140        self._taglist = taglist
141
142        self._level = None
143        self._peakdB = None
144        self._profile = profile
145
146        self._profile.test()
147
148    def start(self, runner):
149        task.Task.start(self, runner)
150
151        # here to avoid import gst eating our options
152        import gst
153
154        self._pipeline = gst.parse_launch('''
155            filesrc location="%s" !
156            decodebin name=decoder !
157            audio/x-raw-int,width=16,depth=16,channels=2 !
158            level name=level !
159            %s !
160            filesink location="%s" name=sink''' % (
161                common.quoteParse(self._inpath).encode('utf-8'),
162                self._profile.pipeline,
163                common.quoteParse(self._outpath).encode('utf-8')))
164
165        tagger = self._pipeline.get_by_name('tagger')
166
167        # set tags
168        if self._taglist:
169            tagger.merge_tags(self._taglist, gst.TAG_MERGE_APPEND)
170
171        self.debug('pausing pipeline')
172        self._pipeline.set_state(gst.STATE_PAUSED)
173        self._pipeline.get_state()
174        self.debug('paused pipeline')
175
176        # get length
177        self.debug('query duration')
178        try:
179            length, qformat = tagger.query_duration(gst.FORMAT_DEFAULT)
180        except gst.QueryError, e:
181            self.setException(e)
182            self.stop()
183            return
184
185        # wavparse 0.10.14 returns in bytes
186        if qformat == gst.FORMAT_BYTES:
187            self.debug('query returned in BYTES format')
188            length /= 4
189        self.debug('total length: %r', length)
190        self._length = length
191
192        # add eos handling
193        bus = self._pipeline.get_bus()
194        bus.add_signal_watch()
195        bus.connect('message::eos', self._message_eos_cb)
196
197        # set up level callbacks
198        bus.connect('message::element', self._message_element_cb)
199        self._level = self._pipeline.get_by_name('level')
200        # add a probe so we can track progress
201        # we connect to level because this gives us offset in samples
202        srcpad = self._level.get_static_pad('src')
203        srcpad.add_buffer_probe(self._probe_handler)
204
205        self.debug('scheduling setting to play')
206        # since set_state returns non-False, adding it as timeout_add
207        # will repeatedly call it, and block the main loop; so
208        #   gobject.timeout_add(0L, self._pipeline.set_state, gst.STATE_PLAYING)
209        # would not work.
210
211        def play():
212            self._pipeline.set_state(gst.STATE_PLAYING)
213            return False
214        self.runner.schedule(0, play)
215
216        #self._pipeline.set_state(gst.STATE_PLAYING)
217        self.debug('scheduled setting to play')
218
219    def _probe_handler(self, pad, buffer):
220        # update progress based on buffer offset (expected to be in samples)
221        # versus length in samples
222        # marshal to main thread
223        self.runner.schedule(0, self.setProgress,
224            float(buffer.offset) / self._length)
225
226        # don't drop the buffer
227        return True
228
229    def _message_eos_cb(self, bus, message):
230        self.debug('eos, scheduling stop')
231        self.runner.schedule(0, self.stop)
232
233    def _message_element_cb(self, bus, message):
234        if message.src != self._level:
235            return
236
237        s = message.structure
238        if s.get_name() != 'level':
239            return
240
241
242        if self._peakdB is None:
243            self._peakdB = s['peak'][0]
244
245        for p in s['peak']:
246            if self._peakdB < p:
247                self._peakdB = p
248
249    def stop(self):
250        # here to avoid import gst eating our options
251        import gst
252
253        self.debug('stopping')
254        self.debug('setting state to NULL')
255        self._pipeline.set_state(gst.STATE_NULL)
256        self.debug('set state to NULL')
257        task.Task.stop(self)
258
259        if self._peakdB:
260            self.peak = math.sqrt(math.pow(10, self._peakdB / 10.0))
Note: See TracBrowser for help on using the repository browser.