Debian Codegraph @

xl/player/gst/sink.py

raw
1 # Copyright (C) 2008-2010 Adam Olsen
2 # Copyright (C) 2013-2015 Dustin Spicuzza
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2, or (at your option)
7 # 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 General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 #
18 #
19 # The developers of the Exaile media player hereby grant permission
20 # for non-GPL compatible GStreamer and Exaile plugins to be used and
21 # distributed together with GStreamer and Exaile. This permission is
22 # above and beyond the permissions granted by the GPL license by which
23 # Exaile is covered. If you modify this code, you may extend this
24 # exception to your version of the code, but you are not obligated to
25 # do so. If you do not wish to do so, delete this exception statement
26 # from your version.
27
28 from gi.repository import GObject
29 from gi.repository import Gst
30
31 from xl import settings
32 from xl.nls import gettext as _
33
34 from . import gst_utils
35
36 import sys
37
38 import logging
39
40 logger = logging.getLogger(__name__)
41
42
43 __all__ = ['SINK_PRESETS', 'create_device', 'get_devices']
44
45
46 SINK_PRESETS = {
47 # fmt: off
48 "auto": {
49 "name": _("Automatic")
50 },
51 "alsa": {
52 "name": "ALSA",
53 "pipe": "alsasink"
54 },
55 "oss": {
56 "name": "OSS",
57 "pipe": "osssink"
58 },
59 "pulse": {
60 "name": "PulseAudio",
61 "pipe": "pulsesink"
62 },
63 "jack": {
64 "name": "JACK",
65 "pipe": "jackaudiosink"
66 },
67 "directsoundsink": {
68 'name': "DirectSound",
69 'pipe': 'directsoundsink'
70 },
71 # TODO: uncomment when gstreamer wasapi plugin is stable
72 #"wasapi": {
73 # 'name': "WASAPI",
74 # 'pipe': 'wasapisink'
75 #},
76 "custom": {
77 "name": _("Custom")
78 }
79 # fmt: on
80 }
81
82
83 def __filter_presets():
84 for name, preset in list(SINK_PRESETS.items()):
85 pipe = preset.get('pipe')
86 if pipe and not Gst.ElementFactory.make(pipe):
87 del SINK_PRESETS[name]
88
89
90 __filter_presets()
91
92
93 # Every audiosink is a bit different...
94 _autodetect_propnames = [
95 'internal_name', # pulseaudio
96 'device_id', # OSX
97 'device_guid', # directsound
98 'device', # wasapi
99 ]
100
101
102 def _gst_device_autodetect():
103 # Linux: support was added in gstreamer 1.4
104 # OSX: support was added in gstreamer 1.10
105 # Windows: support was added in gstreamer 1.14
106
107 dm = Gst.DeviceMonitor.new()
108 dm.add_filter('Audio/Sink', Gst.Caps.new_empty_simple('audio/x-raw'))
109
110 show_all = settings.get_option("player/show_hidden_devices", False)
111 dm.set_show_all_devices(show_all)
112
113 dm.start()
114
115 try:
116 for device in dm.get_devices():
117 for prop in _autodetect_propnames:
118 if hasattr(device.props, prop):
119 device_id = getattr(device.props, prop)
120 break
121 else:
122 continue
123
124 if not device_id:
125 continue
126
127 display_name = device.get_display_name()
128 if hasattr(device.props, 'properties'):
129 api = device.props.properties.get_string('device.api')
130 if api:
131 display_name = '%s [%s]' % (display_name, api)
132
133 # TODO: remove this when wasapi is stable
134 if api == 'wasapi':
135 continue
136
137 if show_all:
138 device_cls = GObject.type_name_from_instance(device.g_type_instance)
139 display_name = '%s (%s)' % (display_name, device_cls)
140
141 yield (display_name, device_id, device.create_element)
142 finally:
143 dm.stop()
144
145
146 def get_devices():
147 """
148 Generator that yields (display_name, internal_name, fn(name)) where
149 fn is a function that will create the audiosink when called
150 """
151
152 yield (
153 _('Automatic'),
154 'auto',
155 lambda name: Gst.ElementFactory.make('autoaudiosink', name),
156 )
157
158 for info in _gst_device_autodetect():
159 yield info
160
161
162 def create_device(player_name, return_errorsink=True):
163 """
164 Creates an audiosink based on the current settings. This will always
165 return an audiosink, but sometimes it will return an audiosink that
166 only sends error messages to the bus.
167
168 ..note:: Only attempts to autoselect if the user has never specified a
169 setting manually. Otherwise, they may be confused when it
170 switches to a new output. For example, if they specified a USB
171 device, and it is removed -- when restarting the program, they
172 would not expect to automatically start playing on the builtin
173 sound.
174 """
175
176 sink_type = settings.get_option('%s/audiosink' % player_name, 'auto')
177 name = '%s-audiosink' % player_name
178 sink = None
179 errmsg = None
180
181 if sink_type == 'auto':
182 specified_device = settings.get_option(
183 '%s/audiosink_device' % player_name, 'auto'
184 )
185
186 for _unused, device_id, create in get_devices():
187 if specified_device == device_id:
188 sink = create(name)
189 break
190
191 if sink is None:
192 errmsg = _("Could not create audiosink (device: %s, type: %s)")
193 errmsg = errmsg % (specified_device, sink_type)
194
195 elif sink_type == 'custom':
196 pipeline = settings.get_option("%s/custom_sink_pipe" % player_name, "")
197 if not pipeline:
198 errmsg = _("No custom pipeline specified!")
199 else:
200 try:
201 sink = CustomAudioSink(pipeline, name)
202 except Exception:
203 errmsg = _("Error creating custom audiosink '%s'") % pipeline
204 logger.exception(errmsg)
205
206 else:
207 preset = SINK_PRESETS.get(sink_type, None)
208 if preset is None:
209 errmsg = _("Invalid sink type '%s' specified") % sink_type
210 else:
211 sink = Gst.ElementFactory.make(preset['pipe'], name)
212 if sink is None:
213 errmsg = _("Could not create sink type '%s'") % preset['pipe']
214
215 if errmsg is not None:
216 logger.error(errmsg)
217 if return_errorsink:
218 sink = _get_error_audiosink(errmsg)
219
220 return sink
221
222
223 def _get_error_audiosink(msg):
224 sink = Gst.ElementFactory.make('fakesink', None)
225
226 def handoff(s, b, p):
227 s.message_full(
228 Gst.MessageType.ERROR,
229 Gst.stream_error_quark(),
230 Gst.StreamError.FAILED,
231 msg,
232 msg,
233 "",
234 "",
235 0,
236 )
237
238 sink.props.signal_handoffs = True
239 sink.props.sync = True
240 sink.connect('handoff', handoff)
241 return sink
242
243
244 class CustomAudioSink(Gst.Bin):
245 """
246 A bin that holds the audio output sink element(s) for a custom
247 defined sink
248 """
249
250 def __init__(self, pipeline, name):
251 Gst.Bin.__init__(self, name='%s-audiosink' % name)
252
253 elems = [Gst.parse_launch(elem.strip()) for elem in pipeline.split('!')]
254
255 for e in elems:
256 self.add(e)
257
258 gst_utils.element_link_many(*elems)
259
260 # GhostPad allows the bin to pretend to be an audio sink
261 ghost = Gst.GhostPad.new("sink", elems[0].get_static_pad("sink"))
262 self.add_pad(ghost)
263
264
265 if sys.platform == 'win32':
266 from . import sink_windows
267
268 priority_boost = sink_windows.get_priority_booster()
269
270 else:
271
272 def priority_boost(player):
273 # only needed on windows
274 pass